﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperJoe.Framework.UnitOfWorkSql;
using WWX.Admin.IDAL;
using WWX.Dto;
using WWX.Dto.Search;
using WWX.Model;

namespace WWX.Admin.DAL
{
    public class DealDAL : BaseDAL, IDealDAL
    {
        public DealDAL(IUnitOfWork uow) : base(uow)
        {
        }

        public void Add(Deal deal)
        {
            var sql = "insert into deals(id,no,objectid,objecttype,memberid,money,accountRemainCash,createdtime,createdby)values(@id,@no,@objectid,@objecttype,@memberid,@money,@accountRemainCash,@createdtime,@createdby)";
            var parameters = new Dictionary<string, object>();

            parameters.Add("id", deal.Id);
            parameters.Add("no", deal.No);
            parameters.Add("objectid", deal.ObjectId);
            parameters.Add("objecttype", deal.ObjectType);
            parameters.Add("memberid", deal.MemberId);
            parameters.Add("money", deal.Money);
            parameters.Add("createdtime", deal.CreatedTime);
            parameters.Add("createdby", deal.CreatedBy);
            parameters.Add("accountRemainCash", deal.AccountRemainCash);

            this.Execute(sql, parameters);
        }

        public List<DealAdminDto> GetPageList(DealAdminSearch search, int pageNo, int pageSize, out int total)
        {
            List<DealAdminDto> retList = null;
            Dictionary<string, object> parameters = null;
            var whereSql = GenerateWhereSql(search, out parameters);

            string totalSql = "select count(1) from deals where 1=1 " + whereSql;
            total = this.GetCount(totalSql, parameters);
            if (total != 0)
            {
                var pagingSql = "select * from deals where 1=1 " + whereSql + " order by createdtime desc limit " + (pageNo - 1) * pageSize + "," + pageSize;

                retList = this.GetModels<DealAdminDto>(pagingSql, parameters);

            }

            return retList ?? new List<DealAdminDto>();
        }

        private string GenerateWhereSql(DealAdminSearch search, out Dictionary<string, object> parameters)
        {
            parameters = this.CreateParameters();
            string sql = "";

            if (search.ObjectType.HasValue)
            {
                sql += " and dealtype=?dealtype";
                parameters.Add("dealtype", (int)search.ObjectType);
            }

            if (search.StartTime.HasValue)
            {
                sql += " and createdtime>=?startTime";
                parameters.Add("startTime", search.StartTime);
            }

            if (search.EndTime.HasValue)
            {
                var date = search.EndTime.Value.Date.AddDays(1);
                sql += " and createdtime<?endtime";
            }

            return sql;
        }
    }
}
